import os

from langchain import hub
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores.chroma import Chroma
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

os.environ["DASHSCOPE_API_KEY"] = "sk-10920ad0a9d542af96353edd7ab3e613"

from langchain_community.llms import Tongyi
# 加载markdown文档
from langchain_community.document_loaders import UnstructuredMarkdownLoader

markdown_path = r"F:\Users\teacher405\Desktop\README.md"
loader = UnstructuredMarkdownLoader(markdown_path)

data = loader.load()
pass

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(data)

from langchain_community.embeddings import DashScopeEmbeddings

embeddings = DashScopeEmbeddings(
    model="text-embedding-v1", dashscope_api_key="sk-10920ad0a9d542af96353edd7ab3e613"
)
vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)

# Retrieve and generate using the relevant snippets of the blog.
retriever = vectorstore.as_retriever()
prompt = hub.pull("rlm/rag-prompt")
# llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
llm = Tongyi()


def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)


rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

result = rag_chain.invoke("请问该平台有哪些内置功能")
print(result)
"""1"""